/**
 * Copyright 2011 Joe Choi, All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tec.data.persistence.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import tao.data.persistence.Field;
import tao.data.persistence.Record;
import tao.data.structure.List;
import tec.data.persistence.ConcreteField;
import tec.data.persistence.ConcreteRecord;
import tec.data.persistence.PersistenceException;
import tec.data.structure.ListControl;

/**
 * @author Joe Choi
 */
class ResultSetAdapter {
	public ResultSetAdapter(ResultSet result) {
		if(result == null) throw new IllegalArgumentException("Adapter: ResultSet may not be null!");
		this.result = result;
		this.heading = createHeading();
	}
	
	public List<Field> getHeading() {
		return(heading);
	}
	
	public Record getRecord() {
		try {
			if(heading.size() != result.getMetaData().getColumnCount()) {
				throw new PersistenceException(
					"ResultSetAdapter: Heading size(" + heading.size() + 
					") not equal to column count(" + result.getMetaData().getColumnCount() + ")"
				);
			}
		
			ListControl<Object> data = new ListControl<Object>();
			for(int i=0; i<heading.size(); i++) {
				data.add(result.getObject(heading.get(i).getSeq()));
			}
			return(new ConcreteRecord(heading, data.getList()));
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
	}
	
	public boolean next() {
		try {
			return(result.next());
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
	}

	public void close() {
		try {
			if(result != null && (! result.isClosed())) result.close();
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
	}
	
	private List<Field> createHeading() {
		try {
			ListControl<Field> fc = new ListControl<Field>();
			for(int i=1; i<=result.getMetaData().getColumnCount(); i++) {
				Field f = new ConcreteField(
					result.getMetaData().getColumnName(i),
					result.getMetaData().getColumnLabel(i),
					result.getMetaData().getColumnType(i), i
				);
				fc.add(f);
			}
			return(fc.getList());
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
	}
	
	private ResultSet result;
	private List<Field> heading;
}
